package com.example.wangzh.developkit.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.daimajia.swipe.SwipeLayout;
import com.daimajia.swipe.adapters.BaseSwipeAdapter;
import com.example.wangzh.developkit.R;
import com.example.wangzh.developkit.model.Message;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by wangzh on 2017/11/6.
 */

public class MessageAdapter extends BaseSwipeAdapter {
    Context context;
    List<Message> messages;
    private LayoutInflater inflater;

    public MessageAdapter(Context context, List<Message> messages) {
        this.context = context;
        this.messages = messages;
        inflater = LayoutInflater.from(context);
    }

    @Override
    public int getSwipeLayoutResourceId(int position) {
        return R.id.swl_message;
    }

    @Override
    public View generateView(int position, ViewGroup parent) {
        return inflater.inflate(R.layout.list_item_swipe, null);
    }

    @Override
    public void fillValues(final int position, View convertView) {
        final ViewHolder viewHolder;
        if (convertView.getTag() == null) {
            viewHolder = new ViewHolder(convertView);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        viewHolder.txt_content.setText(messages.get(position).getContent());
        viewHolder.txt_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewHolder.swl_message.close();
            }
        });
        viewHolder.txt_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewHolder.swl_message.close();
                messages.remove(position);
                notifyDataSetChanged();
            }
        });
    }

    @Override
    public int getCount() {
        return null == messages ? 0 : messages.size();
    }

    @Override
    public Object getItem(int position) {
        return null == messages ? null : messages.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public static class ViewHolder {
        public ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }

        @BindView(R.id.swl_message)
        SwipeLayout swl_message;
        @BindView(R.id.txt_content)
        TextView txt_content;
        @BindView(R.id.txt_cancel)
        TextView txt_cancel;
        @BindView(R.id.txt_delete)
        TextView txt_delete;
    }
}
